import React, { useEffect, useState, useMemo } from 'react'
import Taro, { FC, useRouter } from '@tarojs/taro'
import { View, Image, Text, Button } from '@tarojs/components'
import { AtIcon, AtTabs, AtTabsPane, AtTextarea, AtCurtain } from 'taro-ui'
import api from '@/services/config/index'
import './index.scss'

type AuthType = '实名认证中' | '实名认证通过' | '实名认证失败' | ' 未提交数据' | undefined
type MemoeIdentity = (id: string) => AuthType
interface ItemDetails {
  name: string
  //创建时间
  createAt: string
  // 共享开始时间
  startAt: string
  // 共享结束时间
  deadlineAt: string
  // 是否是党员
  identityLabel: string
  // 物品积分
  sharePoints: string
  // 押金（押积分）
  deposit: string
  // 物品描述
  description: string
  // 库存
  inventory: string
  // 浏览数
  viewNum: string
  userInfo: {
    // 分享数
    shareNum: string
    thumbsUrl: string //用户图像缩略图
    identityCertified: string
    name: string
  }
  imagePath: Array<{
    imagePath: string
  }>
  addressList: {
    addressDetail: string //详细地址
  }
  // 留言列表
  answerList: Array<{
    answerId: string
    answerAt: string
    answer: string
    avatarUrl: string
    name: string
    identityLabel: '0' | '1'
  }>
  // 评论列表
  evaluationList: Array<{
    sellUser: {
      sellName: string
      sellAatarUrl: string
      evaluationContent: string
      createAt: string
    }
    buyUser: {
      buyName: string
      buyAatarUrl: string
      evaluationContent: string
      createAt: string
    }
  }>
  // 点赞数
  voteNum: string
  // 收藏数
  favoriteNum: string
  // 点赞 1 可点 其他 不可点
  isVote: string
  // 收藏 1 可点 其他 不可点
  isFavorite: string
  // 我想要 1 可点 其他 不可点
  isWant: string
  // 是否举报 0 不可点 1 可点（可举报）
  isReport: string
}
const ItemDetails: FC = () => {
  const [itemDetails, setItemDetails] = useState<ItemDetails>({
    name: '',
    //创建时间
    createAt: '',
    // 共享开始时间
    startAt: '',
    // 共享结束时间
    deadlineAt: '',
    identityLabel: '',
    sharePoints: '',
    deposit: '',
    description: '',
    inventory: '',
    viewNum: '',
    userInfo: {
      shareNum: '',
      thumbsUrl: '', //用户图像缩略图
      identityCertified: '',
      name: ''
    },
    imagePath: [
      {
        imagePath: ''
      }
    ],
    addressList: {
      addressDetail: ''
    },
    answerList: [],
    evaluationList: [],
    // 点赞数
    voteNum: '',
    // 收藏
    favoriteNum: '',
    // 是否已经点赞过，0是点赞过，1没有
    isVote: '',
    isFavorite: '',
    isWant: '',
    isReport: ''
  })
  const [current, setCurrent] = useState<number>(0)
  const [leavemsg, setLeavemsg] = useState<string>('')
  const [showleavemsg, setShowleavemsg] = useState<boolean>(false)

  const router = useRouter()
  const { title, shareId } = router.params
  // 物品详情
  function getShareDetail(_shareId) {
    api['itemSharing/getShareDetail']({ shareId: _shareId, action: 1 }).then((res) => {
      setItemDetails(res.data[0])
    })
  }
  useEffect(() => {
    Taro.setNavigationBarTitle({ title })
    getShareDetail(shareId)
  }, [shareId, title])

  const memoeIdentity: MemoeIdentity = useMemo(() => {
    return (id) => {
      switch (id) {
        case '0':
          return '实名认证中'
        case '1':
          return '实名认证通过'
        case '2':
          return '实名认证失败'
        case '3':
          return ' 未提交数据'
      }
    }
  }, [])
  // 添加留言
  function sureLeavemsg() {
    if (!leavemsg) {
      Taro.showToast({ title: '请输入留言', icon: 'none' })
      return
    }
    api['itemSharing/addShareAnswer']({
      shareId: shareId,
      answer: leavemsg
    }).then((_) => {
      setShowleavemsg(false)
      getShareDetail(shareId)
    })
  }
  // 点赞
  function voteShare() {
    api['itemSharing/voteShare']({ shareId: shareId || 14, vote: itemDetails.isVote }).then(
      (res) => {
        try {
          const isVote = res.data[0].isVote
          if (isVote === '1') {
            Taro.showToast({ title: '取消成功', icon: 'none' })
          } else if (isVote === '0') {
            Taro.showToast({ title: '收藏成功', icon: 'none' })
          }
          getShareDetail(shareId)
        } catch (err) {
          Taro.showToast({ title: err, icon: 'none' })
        }
      }
    )
  }
  // 收藏
  function favoriteShare() {
    api['itemSharing/favoriteShare']({
      shareId: shareId || 14,
      favorite: itemDetails.isFavorite
    }).then((res) => {
      try {
        const isFavorite = res.data[0].isFavorite
        if (isFavorite === '1') {
          Taro.showToast({ title: '取消成功', icon: 'none' })
        } else if (isFavorite === '0') {
          Taro.showToast({ title: '点赞成功', icon: 'none' })
        }
        getShareDetail(shareId)
      } catch (err) {
        Taro.showToast({ title: err, icon: 'none' })
      }
    })
  }
  return (
    <View className='itemDetails grey-bgc iphonex-safe-dis'>
      <View className='itemDetails-container white-bgc'>
        {/* 头部 */}
        <View className='b-bottom  tc-flex itemDetails-header'>
          <Image
            src={itemDetails.userInfo.thumbsUrl}
            className='itemDetails-header__avatar'
          ></Image>
          <View className='itemDetails-header__info'>
            <View>
              <Text className='itemDetails-header__info-name'>{itemDetails.name}</Text>
              {itemDetails.identityLabel === '0' ? (
                <AtIcon prefixClass='icon' value='qz' size='18' color='#61bd6b'></AtIcon>
              ) : (
                <AtIcon prefixClass='icon' value='dy' size='18' color='#cc1a16'></AtIcon>
              )}
            </View>
            <View className='itemDetails-header__info-rtime'>发布时间：{itemDetails.createAt}</View>
            <View className='itemDetails-header__info-stime'>
              共享时段：{itemDetails.startAt} 至 {itemDetails.deadlineAt}
            </View>
          </View>
          {Number(itemDetails.inventory) > 0 && (
            <View className='itemDetails-header__state red-color'>可借出</View>
          )}
        </View>
        <View className='itemDetails-integral red-color'>
          <Text className='itemDetails-integral__txt'>积分：{itemDetails.sharePoints}</Text>
          <Text>押积分：{itemDetails.deposit}</Text>
        </View>
        <View>{itemDetails.description}</View>
        <Image src={itemDetails.imagePath[0].imagePath} className='itemDetails-itemimg'></Image>
        <View className='itemDetails-address sb-flex'>
          <View className='flex'>
            <AtIcon prefixClass='icon' value='location' size='15' color='#999999'></AtIcon>
            <View className='itemDetails-address__details'>
              {itemDetails.addressList.addressDetail}
            </View>
          </View>
          <View className='itemDetails-address__stock'>
            库存{itemDetails.inventory}.浏览{itemDetails.viewNum}
          </View>
        </View>
      </View>
      {/* 分享过的物品 */}
      <View className='itemDetails-shareNum sb-flex'>
        <View>
          <View className='itemDetails-shareNum__name'>{itemDetails.name}</View>
          <View className='itemDetails-shareNum__shop'>
            分享过{itemDetails.userInfo.shareNum}件商品
          </View>
          <View>
            <AtIcon
              prefixClass='icon'
              value='yrz'
              size='15'
              color={itemDetails.userInfo.identityCertified === '1' ? ' #2d7cfe' : '#999999'}
            ></AtIcon>
            <Text className='itemDetails-shareNum__state'>
              {memoeIdentity(itemDetails.userInfo.identityCertified)}
            </Text>
          </View>
        </View>
        <Image src={itemDetails.userInfo.thumbsUrl} className='itemDetails-header__avatar'></Image>
      </View>
      {/* 留言和评论 */}
      <View className='itemDetails-leaveMsg'>
        <AtTabs
          current={current}
          tabList={[{ title: '留言' }, { title: '评论' }]}
          onClick={(value) => {
            setCurrent(value)
          }}
        >
          {/* 留言列表 */}
          <AtTabsPane current={current} index={0}>
            {itemDetails.answerList.length > 0 ? (
              <View className='itemDetails-leaveMsg__content'>
                {itemDetails.answerList.map((item) => {
                  return (
                    <View className='itemDetails-leaveMsg__content-list' key={item.answerId}>
                      <View className='flex'>
                        <Image src={item.avatarUrl} className='itemDetails-header__avatar'></Image>
                        <View className='leaveMsg-user'>
                          <View>
                            <Text className='leaveMsg-user__name'>{item.name}</Text>
                            {item.identityLabel === '0' ? (
                              <AtIcon
                                prefixClass='icon'
                                value='qz'
                                size='18'
                                color='#61bd6b'
                              ></AtIcon>
                            ) : (
                              <AtIcon
                                prefixClass='icon'
                                value='dy'
                                size='18'
                                color='#cc1a16'
                              ></AtIcon>
                            )}
                          </View>
                          <View className='leaveMsg-user__time'>{item.answerAt}</View>
                        </View>
                      </View>
                      <View className='itemDetails-leaveMsg__txt'>{item.answer}</View>
                    </View>
                  )
                })}
              </View>
            ) : (
              <View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>
                暂无内容
              </View>
            )}
          </AtTabsPane>
          {/* 评论列表 */}
          <AtTabsPane current={current} index={1}>
            {itemDetails.evaluationList.length > 0 ? (
              <View className='itemDetails-leaveMsg__content'>
                <View className='itemDetails-leaveMsg__content-list'>
                  <View className='flex'>
                    <Image
                      src={itemDetails.evaluationList[0].sellUser.sellAatarUrl}
                      className='itemDetails-header__avatar'
                    ></Image>
                    <View className='leaveMsg-user'>
                      <View>
                        <Text className='leaveMsg-user__name'>
                          {itemDetails.evaluationList[0].sellUser.sellName}
                        </Text>
                      </View>
                      <View className='leaveMsg-user__time'>
                        {itemDetails.evaluationList[0].sellUser.createAt}
                      </View>
                    </View>
                  </View>
                  <View className='itemDetails-leaveMsg__txt'>
                    {itemDetails.evaluationList[0].sellUser.evaluationContent}
                  </View>
                </View>

                <View className='itemDetails-leaveMsg__content-list'>
                  <View className='flex'>
                    <Image
                      src={itemDetails.evaluationList[0].buyUser.buyAatarUrl}
                      className='itemDetails-header__avatar'
                    ></Image>
                    <View className='leaveMsg-user'>
                      <View>
                        <Text className='leaveMsg-user__name'>
                          {itemDetails.evaluationList[0].buyUser.buyName}
                        </Text>
                      </View>
                      <View className='leaveMsg-user__time'>
                        {itemDetails.evaluationList[0].buyUser.createAt}
                      </View>
                    </View>
                  </View>
                  <View className='itemDetails-leaveMsg__txt'>
                    {itemDetails.evaluationList[0].buyUser.evaluationContent}
                  </View>
                </View>
              </View>
            ) : (
              <View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>
                暂无内容
              </View>
            )}
          </AtTabsPane>
        </AtTabs>
      </View>
      <View className='itemDetails-float white-bgc tc-flex iphonex-safe-dis'>
        <View
          className='itemDetails-float__common'
          onClick={voteShare}
          style={{ color: itemDetails.isVote === '0' ? '#c50001' : '#999999' }}
        >
          <AtIcon
            prefixClass='icon'
            value='dzs'
            size='15'
            color={itemDetails.isVote === '0' ? '#c50001' : '#999999'}
          ></AtIcon>
          <View>赞·{itemDetails.voteNum}</View>
        </View>
        <View
          className='itemDetails-float__common grey-color'
          onClick={() => {
            setShowleavemsg(true)
          }}
        >
          <AtIcon prefixClass='icon' value='wdly' size='15' color='#999999'></AtIcon>
          <View>留言</View>
        </View>
        <View
          className='itemDetails-float__common'
          style={{ color: itemDetails.isFavorite === '1' ? '#999999' : '#c50001' }}
          onClick={favoriteShare}
        >
          <AtIcon
            prefixClass='icon'
            value='wdsc'
            size='15'
            color={itemDetails.isFavorite === '1' ? '#999999' : '#c50001'}
          ></AtIcon>
          <View>收藏·{itemDetails.favoriteNum}</View>
        </View>
        {itemDetails.isReport === '1' && (
          <View
            className='itemDetails-float__common grey-color'
            onClick={() => {
              Taro.navigateTo({ url: '/pages/ItemSharing/Report/index?shareId=' + shareId })
            }}
          >
            <AtIcon prefixClass='icon' value='jb' size='15' color='#999999'></AtIcon>
            <View>举报</View>
          </View>
        )}

        {itemDetails.isWant === '1' && (
          <View
            className='itemDetails-float__wish ct'
            onClick={() => {
              Taro.navigateTo({
                url:
                  '/pages/ChartOnline/index?shareId=' +
                  shareId +
                  '&name=' +
                  itemDetails.userInfo.name
              })
            }}
          >
            我想要
          </View>
        )}
      </View>
      {/* 留言input */}
      {showleavemsg && (
        <AtCurtain
          isOpened={showleavemsg}
          onClose={() => {
            setShowleavemsg(false)
          }}
        >
          <View className='itemDetails-leavemsg'>
            <AtTextarea
              value={leavemsg}
              onChange={(value) => {
                setLeavemsg(value)
              }}
              maxLength={100}
              placeholder='请求输入留言'
              fixed
              count
              autoFocus
            />
            <Button
              onClick={(e) => {
                e.stopPropagation()
                sureLeavemsg()
              }}
            >
              确定
            </Button>
          </View>
        </AtCurtain>
      )}
    </View>
  )
}

export default ItemDetails
